package ltd.newbee.mall.controller.admin;

import ltd.newbee.mall.common.ServiceResultEnum;
import ltd.newbee.mall.entity.AdminUser;

import ltd.newbee.mall.service.AdminUserService;
import ltd.newbee.mall.util.KeyUtil;
import ltd.newbee.mall.util.Result;
import ltd.newbee.mall.util.ResultGenerator;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.apache.commons.lang3.StringUtils;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;


@Controller
@RequestMapping("/admin")
public class AdminController {

    @Resource
    private AdminUserService adminUserService;

    @GetMapping({"/login"})
    public String login() {
        return "admin/login";
    }

    @GetMapping({"", "/", "/index", "/index.html"})
    public String index(HttpServletRequest request) {
        request.setAttribute("path", "index");
        return "admin/index";
    }

    @PostMapping(value = "/login")
    public String login(@RequestParam("userName") String userName,
                        @RequestParam("password") String password,
                        @RequestParam("verifyCode") String verifyCode,
                        HttpServletRequest request,
                        Model model,
                        HttpSession session) {
        if (StringUtils.isEmpty(verifyCode)) {
            session.setAttribute("errorMsg", "验证码不能为空");
            return "admin/login";
        }
        if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)) {
            session.setAttribute("errorMsg", "用户名或密码不能为空");
            return "admin/login";
        }
        String kaptchaCode = session.getAttribute("verifyCode") + "";
        if (StringUtils.isEmpty(kaptchaCode) || !verifyCode.equals(kaptchaCode)) {
            session.setAttribute("errorMsg", "验证码错误");
            return "admin/login";
        }


        AdminUser adminUser = adminUserService.login(userName, password);



        if (adminUser != null) {
            session.setAttribute("loginUser", adminUser.getNickName());
            session.setAttribute("loginUserId", adminUser.getAdminUserId());
//            request.setAttribute("adminLimit",adminUser.getAdminUserLimit());
            //session过期时间设置为7200秒 即两小时
            //session.setMaxInactiveInterval(60 * 60 * 2);

            model.addAttribute("adminLimit",adminUser.getAdminUserLimit());
//            System.out.println(model);
            if(adminUser.getAdminUserLimit() == 0) //超管
            {
                session.setAttribute("adminIdentity", "super");
                return "redirect:/admin/index";
            }else
            {
//                model.addAttribute("adminLimit",adminUser.getAdminUserLimit());
                session.setAttribute("adminIdentity", "normal");
                return "redirect:/admin/users";
            }

        } else {
            session.setAttribute("errorMsg", "登录失败");
            return "admin/login";
        }
    }

    @GetMapping("/profile")
    public String profile(HttpServletRequest request) {
        Integer loginUserId = (int) request.getSession().getAttribute("loginUserId");
        AdminUser adminUser = adminUserService.getUserDetailById(loginUserId);
        if (adminUser == null) {
            return "admin/login";
        }
        request.setAttribute("path", "profile");
        request.setAttribute("loginUserName", adminUser.getLoginUserName());
        request.setAttribute("nickName", adminUser.getNickName());
        return "admin/profile";
    }

    @PostMapping("/profile/password")
    @ResponseBody
    public String passwordUpdate(HttpServletRequest request, @RequestParam("originalPassword") String originalPassword,
                                 @RequestParam("newPassword") String newPassword) {
        if (StringUtils.isEmpty(originalPassword) || StringUtils.isEmpty(newPassword)) {
            return "参数不能为空";
        }
        Integer loginUserId = (int) request.getSession().getAttribute("loginUserId");
        if (adminUserService.updatePassword(loginUserId, originalPassword, newPassword)) {
            //修改成功后清空session中的数据，前端控制跳转至登录页
            request.getSession().removeAttribute("loginUserId");
            request.getSession().removeAttribute("loginUser");
            request.getSession().removeAttribute("errorMsg");
            return ServiceResultEnum.SUCCESS.getResult();
        } else {
            return "修改失败";
        }
    }

    @PostMapping("/profile/name")
    @ResponseBody
    public String nameUpdate(HttpServletRequest request, @RequestParam("loginUserName") String loginUserName,
                             @RequestParam("nickName") String nickName) {
        if (StringUtils.isEmpty(loginUserName) || StringUtils.isEmpty(nickName)) {
            return "参数不能为空";
        }
        Integer loginUserId = (int) request.getSession().getAttribute("loginUserId");
        if (adminUserService.updateName(loginUserId, loginUserName, nickName)) {
            return ServiceResultEnum.SUCCESS.getResult();
        } else {
            return "修改失败";
        }
    }

    @GetMapping("/logout")
    public String logout(HttpServletRequest request) {
        request.getSession().removeAttribute("loginUserId");
        request.getSession().removeAttribute("loginUser");
        request.getSession().removeAttribute("errorMsg");
        return "admin/login";
    }

    /**
     * 列表
     */
    @RequestMapping(value = "/admins/list", method = RequestMethod.GET)
    @ResponseBody
    public Result list(@RequestParam Map<String, Object> params) {
        if (StringUtils.isEmpty((CharSequence) params.get("page")) || StringUtils.isEmpty((CharSequence) params.get("limit"))) {
            return ResultGenerator.genFailResult("参数异常！");
        }

        Integer page = Integer.parseInt(String.valueOf(params.get("page")));;
        //Integer limit = (Integer) params.get("limit");
        Integer limit = Integer.parseInt(String.valueOf(params.get("limit")));
        PageRequest pageRequest = PageRequest.of(page - 1, limit);

        return ResultGenerator.genSuccessResult(adminUserService.getAdminPage(pageRequest));
    }

    /**
     * 添加
     */
    @RequestMapping(value = "/admins/save", method = RequestMethod.POST)
    @ResponseBody
    public Result save(@RequestBody AdminUser adminUser) {
        if (
                StringUtils.isEmpty(adminUser.getLoginUserName())
                        || StringUtils.isEmpty(adminUser.getLoginPassword())
                        || StringUtils.isEmpty(adminUser.getNickName())
        ) {
            return ResultGenerator.genFailResult("参数异常！");
        }


//        adminUser.setAdminUserId(KeyUtil.genUniqueKey2());

        String result = adminUserService.save(adminUser);

        if (ServiceResultEnum.SUCCESS.getResult().equals(result)) {
            return ResultGenerator.genSuccessResult();
        } else {
            return ResultGenerator.genFailResult(result);
        }
    }

    /**
     * 修改
     */
    @RequestMapping(value = "/admins/update", method = RequestMethod.POST)
    @ResponseBody
    public Result update(@RequestBody AdminUser adminUser) {
        if (
                StringUtils.isEmpty(adminUser.getLoginUserName())
                || StringUtils.isEmpty(adminUser.getLoginPassword())
                || StringUtils.isEmpty(adminUser.getNickName())
              ) {
            return ResultGenerator.genFailResult("参数异常！");
        }
        String result = adminUserService.modify(adminUser);
        if (ServiceResultEnum.SUCCESS.getResult().equals(result)) {
            return ResultGenerator.genSuccessResult();
        } else {
            return ResultGenerator.genFailResult(result);
        }
    }

    /**
     * 删除
     */
    @RequestMapping(value = "/admins/delete", method = RequestMethod.POST)
    @ResponseBody
    public Result delete(@RequestBody Integer[] ids) {
        if (ids.length < 1) {
            return ResultGenerator.genFailResult("参数异常！");
        }

        try{
//            for (Integer adminId : ids)
//            {
//                String id = String.valueOf(adminId);
//                adminInfoService.deleteById(id);
//            }
            for (Integer adminId : ids)
            {
                adminUserService.deleteById(adminId);
            }
            return ResultGenerator.genSuccessResult();

        }catch(Exception e)
        {
            return ResultGenerator.genFailResult("删除失败");
        }
    }


}
